/**
 * 
 */
package com.service.affiliate.google.test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.oauth2.LocalServerReceiver;
import com.google.api.oauth2.OAuth2Native;
import com.google.api.services.gan.Gan;
import com.google.api.services.gan.model.Advertiser;
import com.google.api.services.gan.model.Advertisers;
import com.google.api.services.gan.model.Link;
import com.google.api.services.gan.model.Links;


//import com.google.api.services.calendar.Calendar;

/**
 * @author iling
 *
 */
public class GoogleAffiliate 
{
    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY = new JacksonFactory();

    
    private String publisherId = "K380716";
    
    private List<String> scopes = Arrays.asList("https://www.googleapis.com/auth/gan");
    
	Gan server;
	
	
	/**
	 * 
	 */
	public GoogleAffiliate() 
	{
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		GoogleAffiliate service = new GoogleAffiliate();
		
		service.handle();

	}

	public void handle()
	{
		try {
			setUp();
			
//			getAdvertisers();
			List<Link> allLinks = getLinks();
			
			
			System.out.println("all Links : " + allLinks.size());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void setUp() throws Exception
	{
	    HttpTransport httpTransport = new NetHttpTransport();
	    JacksonFactory jsonFactory = new JacksonFactory();	    

	    /**
	     * Make sure to update the client_secrets.json file or you will get an error.
	     * See the Java sample code for more information.
	     */
	    Credential credential;
	
		credential = OAuth2Native.authorize(httpTransport, jsonFactory, new LocalServerReceiver(), scopes);
		
		server = new Gan.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName("Your_Application_Name/Version").build();
	}
	
	public Link getLink(Long linkId) throws IOException
	{
		//Set up request

		Link sLink = server.links().get("publishers", "publisherId", linkId).execute();

		if (sLink == null) {
		  System.out.println("Link Not Found!");
		} else {
		  System.out.println("Link Id:" + sLink.getId() + " Link Name:" + sLink.getName());
		}
		
		return sLink;
	}
	
	
	public void createLink(Long advertiserIdAsLong) throws IOException
	{
		Link psl = new Link();
		psl.setKind("gan#Link");
		psl.setAdvertiserId(advertiserIdAsLong);
		psl.setName("linkName");
		psl.setDestinationUrl("destinationUrl");

		Gan.Links.Insert insertRequest = server.links().insert("publishers", "publisherId", psl);
		Link createdPsl = insertRequest.execute();
		if (createdPsl == null) {
		  System.out.println("Link Not Found!");
		} else {
		  System.out
		      .println("Link Id: " + createdPsl.getId() + "Link Name:" + createdPsl.getName());
		}
	}
	
	public List<Link> getLinks() throws IOException
	{
		List<Link> allResults = new ArrayList<Link>();
		
		List<Long> advertiserIds = new ArrayList<Long>();
		
		advertiserIds.add(48080L);

		getLinks(null, allResults, "2012-08-15", advertiserIds);
		
		return allResults;
	}
	
	public void getLinks(String pageToken, List<Link> allResults, String StartDateMin, List<Long> advertiserIds) throws IOException
	{
		//Set up request
//		List<Long> advertiserIds = new ArrayList<Long>();
//		
//		advertiserIds.add(233040L);
		
		Gan.Links.List request = server.links().list("publishers", publisherId);

		request.setMaxResults(100L);
		
		if(advertiserIds != null)
			request.setAdvertiserId(advertiserIds);
		
		if(StartDateMin != null)
			request.setStartDateMin(StartDateMin + "T00:00:01.000Z");
		
		if(pageToken != null){
			request.setPageToken(pageToken);
		}
		
		//Execute request
		Links links = request.execute();
		
		if(links == null){
			System.out.println("No request Returned!");
		}else{
			System.out.println("getMaxResults = " + request.getMaxResults());
			links.getNextPageToken();
			
			List<Link> results = links.getItems();
			if (results == null) {
			  System.out.println("No Results Returned!");
			} else {
				allResults.addAll(results);
				
				if(links.getNextPageToken() != null){
					getLinks(links.getNextPageToken(), allResults, StartDateMin, advertiserIds);
				}
				  for (Link e : results) {
					  System.out.println("************************************************************************************************************");
					  
					  System.out.println("Link ID: " + e.getId() + " Link Name: " + e.getName());
					  System.out.println("getCreativeType: " + e.getCreativeType());
					  System.out.println("getDuration: " + e.getDuration());
					  System.out.println("getDestinationUrl: " + e.getDestinationUrl());
					  System.out.println("getDescription: " + e.getDescription());
					  System.out.println("getImageAltText: " + e.getImageAltText());
					  System.out.println("getPromotionType: " + e.getPromotionType());
					  System.out.println("getAdvertiserId: " + e.getAdvertiserId());
					  
					  System.out.println("getKind: " + e.getKind());
					  System.out.println("getIsActive: " + e.getIsActive());
					  
					  System.out.println("getCreateDate: " + e.getCreateDate());
					  System.out.println("getStartDate: " + e.getStartDate());
					  System.out.println("getEndDate: " + e.getEndDate());
					  
					  Map<String, Object> unknown = e.getUnknownKeys();

					  for(Entry<String, Object> entry : unknown.entrySet()){
						  System.out.println("key: " + entry.getKey() + " value: " + entry.getValue().toString());
					  }
				  }
			}
		}
	}
	
	public List<Advertiser> getAdvertisers() throws IOException
	{
		//Set up request
		Gan.Advertisers.List request = server.advertisers().list("publishers", publisherId);
		request.setMaxResults(100l);
		
		
		//Execute request
		List<Advertiser> results = request.execute().getItems();
		if (results == null) {
			System.out.println("No Results Returned!");
		} else {
			for (Advertiser a : results) {
				System.out.println("************************************************************************************************************");
				System.out.println("Advertiser ID: " + a.getId() + " Advertiser Name: " + a.getName());
				System.out.println("getCategory: " + a.getCategory());
				System.out.println("getSiteUrl: " + a.getSiteUrl());
				System.out.println("getContactEmail: " + a.getContactEmail());
				System.out.println("getContactPhone: " + a.getContactPhone());
				System.out.println("getPayoutRank: " + a.getPayoutRank());
				System.out.println("getLogoUrl: " + a.getLogoUrl());
				System.out.println("getStatus: " + a.getStatus());
				System.out.println("getDescription: " + a.getDescription());
				
				 Map<String, Object> unknown = a.getUnknownKeys();
				for(Entry<String, Object> entry : unknown.entrySet()){
					  System.out.println("key: " + entry.getKey() + " value: " + entry.getValue().toString());
				}
			}
		}
		
		return results;
	}
	
	
	
	public void setUp2()
	{
		try {
		    HttpTransport httpTransport = new NetHttpTransport();
		    JacksonFactory jsonFactory = new JacksonFactory();
	
		    // The clientId and clientSecret are copied from the API Access tab on
		    // the Google APIs Console
		    String clientId = "126738922261.apps.googleusercontent.com";
		    String clientSecret = "aT_kmncInPPNVCxEMidx5h58";
	
		    // Or your redirect URL for web based applications.
		    String redirectUrl = "urn:ietf:wg:oauth:2.0:oob";
		    String scope = "https://www.googleapis.com/auth/gan.readonly";
	
		    // Step 1: Authorize -->
//		    String authorizationUrl = new GoogleAuthorizationRequestUrl(clientId, redirectUrl, scope).build();
//	
//		    // Point or redirect your user to the authorizationUrl.
//		    System.out.println("Go to the following link in your browser:");
//		    System.out.println(authorizationUrl);
//	
//		    // Read the authorization code from the standard input stream.
//		    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//		    System.out.println("What is the authorization code?");
//		    String code = in.readLine();
		    // End of Step 1 <--
	
		    
		    
		    String code = "4/-glVsDkn__oT4wlRYiA-aXAYwLzx.0lZvj161EkgcuJJVnL49Cc9MKl_rcgI";
		    // Step 2: Exchange -->
		    AccessTokenResponse response = new GoogleAuthorizationCodeGrant(httpTransport, jsonFactory,
		        clientId, clientSecret, code, redirectUrl).execute();
		    // End of Step 2 <--
	
		    GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
		        response.accessToken, httpTransport, jsonFactory, clientId, clientSecret,
		        response.refreshToken);
	
		    
		    
	//	    Calendar service = new Calendar(httpTransport, accessProtectedResource, jsonFactory);
	//	    service.setApplicationName("YOUR_APPLICATION_NAME");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  }
}
